{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline\n",
    "from datasets import load_dataset\n",
    "\n",
    "class WhisperModel(object):\n",
    "    def __init__(self) -> None:\n",
    "        device = \"cuda:0\" if torch.cuda.is_available() else \"cpu\"\n",
    "        torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32\n",
    "        model_id = \"/data/models/huggingface/whisper-large-v3\"\n",
    "        model = AutoModelForSpeechSeq2Seq.from_pretrained(\n",
    "            model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True\n",
    "        )\n",
    "        model.to(device)\n",
    "        processor = AutoProcessor.from_pretrained(model_id)\n",
    "        self.SpeechToEngPipe = pipeline(\n",
    "            \"automatic-speech-recognition\",\n",
    "            model=model,\n",
    "            tokenizer=processor.tokenizer,\n",
    "            feature_extractor=processor.feature_extractor,\n",
    "            torch_dtype=torch_dtype,\n",
    "            device=device,\n",
    "        )\n",
    "        self.TranslatePipe = pipeline(\"translation_en_to_zh\", model=\"/data/models/huggingface/opus-mt-en-zh\",device=0)\n",
    "\n",
    "    def speech2chinese(self,eng_speech):\n",
    "        result = self.SpeechToEngPipe(eng_speech)\n",
    "        print(result[\"text\"])\n",
    "        ch_result = self.TranslatePipe(result[\"text\"])[0][\"translation_text\"]\n",
    "        return ch_result\n",
    "\n",
    "wm = WhisperModel()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " I was so proud for you.\n",
      "[{'translation_text': '我为你感到骄傲'}]\n"
     ]
    }
   ],
   "source": [
    "sameng_speechple = \"1.mp3\"\n",
    "print(wm.speech2chinese(sameng_speechple))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
